import java.io.*;
import java.util.ArrayList;
import java.util.List;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;


public class Searcher {
	
	private int numPages;
	private Query q;
	private int resultsPerPage;
	private ArrayList<Tweet> results;
	
	public Searcher(){
		setNumPages(10);
		setQuery("Twitter");
		setResultsPerPage(10);
		results = null;
	}
	
	public Searcher (String searchTerm, int pages, int resultsPerPage){
		setNumPages(pages);
		setQuery(searchTerm);
		setResultsPerPage(resultsPerPage);
		results = null;
	}

	public int getNumPages() {
		return numPages;
	}

	public void setNumPages(int numPages) {
		this.numPages = numPages;
	}
	
	public void setResultsPerPage(int rpp){
		this.resultsPerPage = rpp;
	}

	public void setQuery(String s){
		this.q = new Query(s);
	}
	
	private void setResults(ArrayList<Tweet> r) {
		this.results = r;
	}
	
	public ArrayList<Tweet> getResults() {
		return results;
	}
	
	public void enableHashSearch() {
		this.q = new Query("#" + this.q.getQuery());
	}
	
	
	public void searchTweets(){
		Twitter twitter = new TwitterFactory().getInstance();
		q.rpp(resultsPerPage);
		QueryResult result = null;
		
		for(int i = 0; i<numPages; i++){
			q.setPage(i+1);
		try {
				result = twitter.search(q);
			} catch (TwitterException e) {
				System.err.println("Search Failed!");
			}
			System.out.println("-----------Page "+ (i+1) + "----------------");
			List <Tweet> tweets = result.getTweets();
			setResults((ArrayList<Tweet>)tweets);
			for(Tweet t : tweets){
				System.out.println(t.getText() + "\n");
			}
		}
	}
	
	public void writeSearchToFile(String fileName){
		try {
			OutputStream output = new FileOutputStream(fileName);
			PrintStream print = new PrintStream(output);
			System.setOut(print);
			
		} catch (IOException e) {
			System.err.println("failed to open IO stream");
		}
		searchTweets();
	}
	
	public static void main(String[] args) {
		Searcher s = new Searcher();
		s.writeSearchToFile("results.txt");
	}
	
}
